package cn.edu.zafu.bigdata.llc;

import java.io.*;
import java.util.*;

public class RhymingWords {
    public static void main(String[] args) throws IOException {
        FileReader words = new FileReader("words.txt");
        // 进行单词的逆序、排序、再逆序还原
        Reader rhymedWords = reverse(sort(reverse(words)));

        // 将处理后的单词列表输出显示
        BufferedReader in = new BufferedReader(rhymedWords);
        String input;
        while ((input = in.readLine()) != null) {
            System.out.println(input);
        }
        in.close();
    }

    // 创建管道，创建并启动单词逆序线程
    public static Reader reverse(Reader source) throws IOException {
        BufferedReader in = new BufferedReader(source);
        PipedWriter pipeOut = new PipedWriter();
        PipedReader pipeIn = new PipedReader(pipeOut);
        PrintWriter out = new PrintWriter(pipeOut);
        new ReverseThread(out, in).start();
        return pipeIn;
    }

    // 创建管道，创建并启动单词排序线程
    public static Reader sort(Reader source) throws IOException {
        BufferedReader in = new BufferedReader(source);
        PipedWriter pipeOut = new PipedWriter();
        PipedReader pipeIn = new PipedReader(pipeOut);
        PrintWriter out = new PrintWriter(pipeOut);
        new SortThread(out, in).start();
        return pipeIn;
    }
}

// 逆序线程
class ReverseThread extends Thread {
    private final PrintWriter out;
    private final BufferedReader in;

    public ReverseThread(PrintWriter out, BufferedReader in) {
        this.out = out;
        this.in = in;
    }

    @Override
    public void run() {
        try {
            String line;
            while ((line = in.readLine()) != null) {
                // 逆序处理每行
                StringBuilder reversedLine = new StringBuilder(line);
                out.println(reversedLine.reverse());
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 排序线程
class SortThread extends Thread {
    private final PrintWriter out;
    private final BufferedReader in;

    public SortThread(PrintWriter out, BufferedReader in) {
        this.out = out;
        this.in = in;
    }

    @Override
    public void run() {
        try {
            List<String> lines = new ArrayList<>();
            String line;
            while ((line = in.readLine()) != null) {
                lines.add(line);
            }

            // 排序操作
            Collections.sort(lines);

            // 输出排序后的结果
            for (String sortedLine : lines) {
                out.println(sortedLine);
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
